/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Services;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entity.Appointment;
import Entity.Veterinarian;
import Services.exceptions.NonexistentEntityException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Grace
 */
public class VeterinarianService implements Serializable {

    public VeterinarianService(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Veterinarian veterinarian) {
        if (veterinarian.getAppointments() == null) {
            veterinarian.setAppointments(new ArrayList<Appointment>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Appointment> attachedAppointments = new ArrayList<Appointment>();
            for (Appointment appointmentsAppointmentToAttach : veterinarian.getAppointments()) {
                appointmentsAppointmentToAttach = em.getReference(appointmentsAppointmentToAttach.getClass(), appointmentsAppointmentToAttach.getId());
                attachedAppointments.add(appointmentsAppointmentToAttach);
            }
            veterinarian.setAppointments(attachedAppointments);
            em.persist(veterinarian);
            for (Appointment appointmentsAppointment : veterinarian.getAppointments()) {
                Veterinarian oldVeterinarianOfAppointmentsAppointment = appointmentsAppointment.getVeterinarian();
                appointmentsAppointment.setVeterinarian(veterinarian);
                appointmentsAppointment = em.merge(appointmentsAppointment);
                if (oldVeterinarianOfAppointmentsAppointment != null) {
                    oldVeterinarianOfAppointmentsAppointment.getAppointments().remove(appointmentsAppointment);
                    oldVeterinarianOfAppointmentsAppointment = em.merge(oldVeterinarianOfAppointmentsAppointment);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Veterinarian veterinarian) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Veterinarian persistentVeterinarian = em.find(Veterinarian.class, veterinarian.getId());
            List<Appointment> appointmentsOld = persistentVeterinarian.getAppointments();
            List<Appointment> appointmentsNew = veterinarian.getAppointments();
            List<Appointment> attachedAppointmentsNew = new ArrayList<Appointment>();
            for (Appointment appointmentsNewAppointmentToAttach : appointmentsNew) {
                appointmentsNewAppointmentToAttach = em.getReference(appointmentsNewAppointmentToAttach.getClass(), appointmentsNewAppointmentToAttach.getId());
                attachedAppointmentsNew.add(appointmentsNewAppointmentToAttach);
            }
            appointmentsNew = attachedAppointmentsNew;
            veterinarian.setAppointments(appointmentsNew);
            veterinarian = em.merge(veterinarian);
            for (Appointment appointmentsOldAppointment : appointmentsOld) {
                if (!appointmentsNew.contains(appointmentsOldAppointment)) {
                    appointmentsOldAppointment.setVeterinarian(null);
                    appointmentsOldAppointment = em.merge(appointmentsOldAppointment);
                }
            }
            for (Appointment appointmentsNewAppointment : appointmentsNew) {
                if (!appointmentsOld.contains(appointmentsNewAppointment)) {
                    Veterinarian oldVeterinarianOfAppointmentsNewAppointment = appointmentsNewAppointment.getVeterinarian();
                    appointmentsNewAppointment.setVeterinarian(veterinarian);
                    appointmentsNewAppointment = em.merge(appointmentsNewAppointment);
                    if (oldVeterinarianOfAppointmentsNewAppointment != null && !oldVeterinarianOfAppointmentsNewAppointment.equals(veterinarian)) {
                        oldVeterinarianOfAppointmentsNewAppointment.getAppointments().remove(appointmentsNewAppointment);
                        oldVeterinarianOfAppointmentsNewAppointment = em.merge(oldVeterinarianOfAppointmentsNewAppointment);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = veterinarian.getId();
                if (findVeterinarian(id) == null) {
                    throw new NonexistentEntityException("The veterinarian with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Veterinarian veterinarian;
            try {
                veterinarian = em.getReference(Veterinarian.class, id);
                veterinarian.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The veterinarian with id " + id + " no longer exists.", enfe);
            }
            List<Appointment> appointments = veterinarian.getAppointments();
            for (Appointment appointmentsAppointment : appointments) {
                appointmentsAppointment.setVeterinarian(null);
                appointmentsAppointment = em.merge(appointmentsAppointment);
            }
            em.remove(veterinarian);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Veterinarian> findVeterinarianEntities() {
        return findVeterinarianEntities(true, -1, -1);
    }

    public List<Veterinarian> findVeterinarianEntities(int maxResults, int firstResult) {
        return findVeterinarianEntities(false, maxResults, firstResult);
    }

    private List<Veterinarian> findVeterinarianEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Veterinarian.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    
    public Veterinarian findVeterinarianEntitiesByNameOrSsn(String name){
        EntityManager em = getEntityManager();
        Query query = em.createQuery("select o from Person o where o.idPerson.name=:name or o.idPerson.ssn=:ssn").setParameter("name", name).setParameter("ssn", name);
        if(!query.getResultList().isEmpty()) {
            return (Veterinarian) query.getSingleResult();
        }
        else{
            return null;
        }
    }

    public Veterinarian findVeterinarian(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Veterinarian.class, id);
        } finally {
            em.close();
        }
    }

    public int getVeterinarianCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Veterinarian> rt = cq.from(Veterinarian.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
